import React, { useEffect, useState } from "react";
import '../../appcommon.css';
import styles from './passwordchanged.module.css';
import { useDispatch } from "react-redux";
import { DotLoading, Mask, Toast } from "antd-mobile";
import { saveEvent } from "@/store/actions/saveEvent";
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";
import ZjcUtil from "@/utils/zjcUtil";
import AppParams from "@/utils/appParams";
import { doLogin } from "@/store/actions/login";
import { LangThai } from '@/utils/langThai';
import { chagePassword } from "@/store/actions/changePassword";
import { useFormik } from "formik";
import NavigateBar from "@/components/NavigateBar";

/**
 * 修改密码-输入新密码页
 */
export default function PasswordNewInput() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    // zjc 输入内容
    const [zjcValue, setZjcValue] = useState('')

    // 文案翻译
    const [curLang, setCurLang] = useState(LangThai);

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //router
    const history = useHistory()

    // Formik 表单对象
    const form = useFormik({
        //设置表单初始值
        initialValues: {
            oldPassword: '',
            newPassword: '',
            newPasswordConfirm: ''
        },

        //提交
        onSubmit: values => {
            console.log(values)

            //提交登录
            onChangePasswordSubmit()
        },

        //校验
        validate(values) {
            const errors = {}

            let goldPassword = values.oldPassword || ""
            let gnewPassword = values.newPassword || ""
            let gnewPasswordConfirm = values.newPasswordConfirm || ""

            // 非空
            if (goldPassword.length < 8) {
                errors.oldPassword = curLang.loginPasswordMustNotEmpty
            }

            // 非空
            if (gnewPassword.length < 8) {
                errors.newPassword = curLang.loginPasswordMustNotEmpty
            }

            // 非空
            if (gnewPasswordConfirm.length < 8) {
                errors.newPasswordConfirm = curLang.loginPasswordMustNotEmpty
            }

            if ((gnewPassword.length > 0) && (gnewPasswordConfirm.length > 0)) {
                // 不一致
                if (gnewPassword !== gnewPasswordConfirm) {
                    errors.newPasswordConfirm = curLang.meConfirmPasswordNotSame
                }
            }

            return errors
        }
    });

    //清空登录信息
    useEffect(() => {
        //关闭loading
        setMaskVisible(false)

        //打点
        doHitEvent("PASSWORD_NEW_INPUT_START")

        return () => {
            //打点
            doHitEvent("PASSWORD_NEW_INPUT_END")
        }
    }, [])

    // 点击提交
    const onChangePasswordSubmit = () => {
        console.log("点击提交");

        // 直接登录
        let inputResult = isInputCorrect();
        if (!inputResult) {
            history.replace('/passwordzjcinput');
            return;
        }

        // 登录
        doChangePassword(inputResult.oldPassword, inputResult.newPassword);
    };

    // 修改密码返回
    const onDoChangePasswordCallback = (success, data, isNeedToReLogin) => {
        //关闭loading
        setMaskVisible(false)
        console.log('修改密码返回: ' + success);

        if (success) {
            // 处理流程业务
            Toast.show(curLang.meChangePasswordSuccess);

            setTimeout(()=>{
                console.log('跳转首页');
                history.replace('/home');
            }, 1000);
        } else {
            if (isNeedToReLogin) {
                history.replace('/login')
            }
        }
    };

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //请求登录接口
    const doChangePassword = async (oldPassword, newPassword) => {
        console.log("doLogin: " + oldPassword + " , " + newPassword);

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = chagePassword(oldPassword, newPassword, onDoChangePasswordCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 判断输入是否合法
    const isInputCorrect = () => {
        //验证手机号
        let oldPassword = form.values.oldPassword;
        let newPassword = form.values.newPassword;
        let newPasswordConfirm = form.values.newPasswordConfirm;
        let zjc = ZjcUtil.zjc;

        if (!zjc || (zjc.length < 4)) {
            return null;
        }

        if (!oldPassword || (oldPassword.length < 8)) {
            return null;
        }

        if (!newPassword || (newPassword.length < 8)) {
            return null;
        }

        if (!newPasswordConfirm || (newPasswordConfirm.length < 8)) {
            return null;
        }

        if (newPassword !== newPasswordConfirm) {
            return null;
        }

        return { oldPassword: oldPassword, newPassword: newPassword, newPasswordConfirm: newPasswordConfirm, zjc: zjc };
    };

    return (
        <div className="pageRoot">
            <NavigateBar theme="white" showLogout={false} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>{curLang.meChangePassword}</NavigateBar>

            <div className={styles.passwordListRoot}>

                {/* zjc 列表 */}
                <form className={styles.passwordVerifyList} onSubmit={form.handleSubmit}>

                    {/* 第1行 */}
                    <div className={styles.passwordListVerifyContent}>
                        <div className={styles.passwordListMenuTitle}>{curLang.meOldPassword}</div>
                        <input
                            className={styles.passwordListPassowrdInputContent}
                            id="oldPassword"
                            name="oldPassword"
                            placeholder={curLang.appPassword}
                            type="text"
                            value={form.values.oldPassword}
                            onBlur={form.handleBlur}
                            onChange={form.handleChange}
                            autoComplete="off" />
                    </div>
                    {form.errors.oldPassword && form.touched.oldPassword && (
                        <div className={styles.passwordListValidate}>{form.errors.oldPassword}</div>
                    )}

                    {/* 第2行 */}
                    <div className={styles.passwordListVerifyContent}>
                        <div className={styles.passwordListMenuTitle}>{curLang.meNewPassword}</div>
                        <input
                            className={styles.passwordListPassowrdInputContent}
                            id="newPassword"
                            name="newPassword"
                            placeholder={curLang.appPassword}
                            type="text"
                            value={form.values.newPassword}
                            onBlur={form.handleBlur}
                            onChange={form.handleChange}
                            autoComplete="off" />
                    </div>
                    {form.errors.newPassword && form.touched.newPassword && (
                        <div className={styles.passwordListValidate}>{form.errors.newPassword}</div>
                    )}

                    {/* 第3行 */}
                    <div className={styles.passwordListVerifyContent}>
                        <div className={styles.passwordListMenuTitle}>{curLang.meConfirmPassword}</div>
                        <input
                            className={styles.passwordListPassowrdInputContent}
                            id="newPasswordConfirm"
                            name="newPasswordConfirm"
                            placeholder={curLang.appPassword}
                            type="text"
                            value={form.values.newPasswordConfirm}
                            onBlur={form.handleBlur}
                            onChange={form.handleChange}
                            autoComplete="off" />
                    </div>
                    {form.errors.newPasswordConfirm && form.touched.newPasswordConfirm && (
                        <div className={styles.passwordListValidate}>{form.errors.newPasswordConfirm}</div>
                    )}
                </form>

                {/* 提交 */}
                <div className="pageBtnSubmit pageMarginTop16px" onClick={form.handleSubmit}>{curLang.zjcInputNext}</div>

                {/* 底部提示 */}

                {/* 底部 margin */}
                <div className="pageBottomEdge"></div>
            </div>

            {/* load mask */}
            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="pageLoadingOverlayContent">
                    <span style={{ fontSize: 24, color: '#3498DB' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div >
    )
}